﻿using System;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Configuration;
using Medianamik.Core.Profile;
using Medianamik.Globalization;
using Telerik.Web.UI;

namespace Medianamik.UI.Controls
{
    class TemplatePicker : CompositeControl
    {

        #region Fields

        readonly HtmlGenericControl _previewFrame = new HtmlGenericControl("iframe");
        readonly ListBox _templateList = new ListBox();
        readonly HiddenField hiddenField = new HiddenField();
        private static readonly MedianamikConfigSection _config = (MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK);
       
        #endregion

        #region Events

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            
            string cultureName = _config.DefaultEditionCultureName;

            if (Page.User.Identity.IsAuthenticated)
            {
                var profile = (UserProfile)HttpContext.Current.Profile;

                if (!string.IsNullOrEmpty(profile.UICultureName))
                    cultureName = profile.UICultureName;
            }

            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(cultureName);
        }

        void SelectedTemplateChanged(object sender, EventArgs e)
        {
            DisplayTemplatePreview();
        }

        #endregion

        #region Properties

        public string CssFilePath
        {
            get
            {
                return ViewState["CssFilePath"] as string;
            }
            set
            {
                ViewState["CssFilePath"] = value;
            }
        }

        #endregion

        #region Methods

        private void DisplayTemplatePreview()
        {
            _previewFrame.Attributes.Add("src", String
                .Format("template.tpl?id={0}&css={1}",
                _templateList.SelectedValue, CssFilePath));
        }

        protected override void CreateChildControls()
        {
            Controls.Add(new RadAjaxManager());

            var medianamikCss = new Literal();
            Controls.Add(medianamikCss);
            

            #region Main Div

            var mainDiv = new HtmlGenericControl("div");
            Controls.Add(mainDiv);
            mainDiv.Attributes.Add("class", "CorpsPopup");

            #region Choix du template

            var templateSelectDiv = new HtmlGenericControl("div");
            mainDiv.Controls.Add(templateSelectDiv);
            templateSelectDiv.Attributes.Add("class", "ChoixTemplate");

            templateSelectDiv.Controls.Add(_templateList);

            _templateList.SelectedIndexChanged += SelectedTemplateChanged;

            #endregion

            mainDiv.Controls.Add(_previewFrame);

            #region Buttons

            var buttonsCssLiteral1 = new Literal();
            mainDiv.Controls.Add(buttonsCssLiteral1);
            var selectButton = new Button();
            mainDiv.Controls.Add(selectButton);
            var space = new Literal();
            mainDiv.Controls.Add(space);
            var cancelButton = new Button();
            mainDiv.Controls.Add(cancelButton);
            var buttonsCssLiteral2 = new Literal();
            mainDiv.Controls.Add(buttonsCssLiteral2);

            #endregion

            #endregion

            Controls.Add(hiddenField);


            if (!Page.IsPostBack) //ViewState s'en occupe
            {
                //CSS pour la window
                medianamikCss.Text = String.Format(@"
                    <link rel=""stylesheet"" type=""text/css"" media=""all"" href=""/Medianamik/includes/medianamik.css?v={0}"" />",
                    Utility.GetFileVersion());
                
                #region Choix du template
               
                DialogParameters p = DialogHandler.GetDialogParameters(this);

                var websiteID = (string)p["website"];
                CssFilePath = (string)p["css"];
                if (!string.IsNullOrEmpty(websiteID))
                {
                    _templateList.AutoPostBack = true;
                    _templateList.DataSource = ConfigManager.GetAll<MedianamikTemplate>().Where(tpl => tpl.WebSite.ID.ToString() == websiteID);
                    _templateList.DataTextField = "DisplayName";
                    _templateList.DataValueField = "ID";
                    _templateList.DataBind();
                    _templateList.CssClass = "SelectListPopupGabarit";
                    if (_templateList.Items.Count > 0)
                    {
                        _templateList.SelectedIndex = 0;
                        DisplayTemplatePreview();
                    }
                }
                #endregion

                _previewFrame.Attributes.Add("class", "IframePopup");
                _previewFrame.Attributes.Add("frameborder", "0");

                #region Buttons

                selectButton.Text = Translator.Translate("Medianamik_ContentManagement", "MedianamikTemplateSelect");
                selectButton.OnClientClick = "insertLink();";
                selectButton.CssClass = "Btn";

                space.Text = "&nbsp;";

                cancelButton.Text = Translator.Translate("Medianamik_ContentManagement", "MedianamikTemplateCancel");
                cancelButton.OnClientClick = "getRadWindow().close();";
                cancelButton.CssClass = "Btn";

                buttonsCssLiteral1.Text = "<p style=\"clear:both; margin-top: 20px;\">";
                buttonsCssLiteral2.Text = "</p>";

                #endregion
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<script type=\"text/javascript\">\n");
            writer.Write("function getRadWindow(){\n");
            writer.Write("if (window.radWindow){return window.radWindow;}\n");
            writer.Write("if (window.frameElement && window.frameElement.radWindow){return window.frameElement.radWindow;}\n");
            writer.Write("return null;}\n");

            writer.Write(@"function initDialog(){
                var args =getRadWindow().ClientParameters;
                var hiddenField = document.getElementById('" + hiddenField.ClientID + @"');
                hiddenField.value = args['css'];");
            writer.Write("}");

            writer.Write("if (window.attachEvent){window.attachEvent(\"onload\", initDialog);}\n");
            writer.Write("else if (window.addEventListener){window.addEventListener(\"load\", initDialog, false);}\n");

            writer.Write("function insertLink(){\n");
            writer.Write("var closeArgument = {}; closeArgument.content = getContentFromIframe();");
            writer.Write("getRadWindow().close(closeArgument);}");

            writer.Write("function getContentFromIframe(){\n");
            writer.Write("var myIFrame = $get('" + _previewFrame.ClientID + "');\n");
            writer.Write("return myIFrame.contentWindow.document.body.innerHTML;\n");
            writer.Write("}");
            writer.Write("</script>\n");

            base.Render(writer);
        }

        #endregion


    }


}
